<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表 -->
            <el-table :data="roleList" border stripe>
                <!-- 下拉功能 -->
                <el-table-column type="expand">
                    <template v-slot='slotProps'>
                        <!-- <pre>{{slotProps.row}}</pre> -->
                        <el-row v-for="(i,index) in slotProps.row.children" :key="i.id" 
                        :class="['bdbottom',index===0 ? 'bdtop' : '' ,'vcenter']">
                            <!-- 渲染一级权限（栅格布局默认24列，设置:span属性占5列） -->
                            <el-col :span="5">
                                <el-tag closable @close='removeRightById(slotProps.row, i.id)'>{{i.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <!-- 嵌套for循环，渲染二级权限 -->
                                <el-row v-for="j in i.children" :key="j.id" class="vcenter">
                                    <el-col :span="6">
                                        <el-tag type="success"
                                        closable @close='removeRightById(slotProps.row, j.id)'>{{j.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!-- 嵌套for循环，渲染三级权限 -->
                                        <el-tag v-for="k in j.children" :key="k.id" type="warning" 
                                        closable @close='removeRightById(slotProps.row, k.id)'>
                                            {{k.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作"> 
                    <template v-slot='slotProps'>
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                        @click="showEditRole(slotProps.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                        @click="removeRoleById(slotProps.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                        @click="showSetRightDialog(slotProps.row)">分配权限</el-button>
                    </template>    
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色的对话框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%"
            @close='addDialogClose()'>
            <!-- 填写内容 -->
            <el-form :model="addRoleForm" :rules="addFormRules" ref="addRolesRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部确认/取消按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色时的对话框 -->
        <el-dialog
            title="编辑用户信息"
            :visible.sync="editDialogVisible"
            width="50%"
            @close='editDialogClose()'>
            <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="70px">
                <el-form-item label="角色ID"> <!--不需要prop校验规则（禁用的）-->
                    <el-input v-model="editRoleForm.roleId" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限时的对话框 -->
        <el-dialog
            title="分配权限"
            :visible.sync="setRightDialogVisible"
            width="50%"
            @close='setRightDialogClose()'>
            <!-- 树形空间 -->
            <el-tree :data="setRightsList" :props="treeProps" ref="setRightsTreeRef"
            show-checkbox
            node-key='id'
            :default-checked-keys="defKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name:'Roles',
    data() {
        return {
            // 所有角色列表数据
            roleList:[],
            // 添加角色对话框的显示和隐藏
            addDialogVisible:false,
            // 添加角色的表单数据
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
            // 添加角色的表单的验证规则
            addFormRules:{
                roleName:[{ required: true, message: '请输入角色名称', trigger: 'blur' }],
                roleDesc:[{ required: true, message: '请输入角色描述', trigger: 'blur' }]
            },
            // 编辑角色对话框的显示和隐藏
            editDialogVisible:false,
            // 编辑角色的表单数据
            editRoleForm:[],
            // 编辑角色的表单的验证规则
            editRoleRules:{
                roleName:[{ required: true, message: '请输入角色名称', trigger: 'blur' }],
                roleDesc:[{ required: true, message: '请输入角色描述', trigger: 'blur' }]
            },
            // 分配权限对话框的显示和隐藏
            setRightDialogVisible:false,
            // 分配权限的表单数据
            setRightsList:[],
            // 用el-tree时的配置项
            treeProps:{
                children:'children',
                label:'authName'
            },
            // 树形控件中默认选中的权限
            defKeys:[],
            // 当前即将分配权限的角色ID
            roleId:''
        }
    },
    methods: {
        // 获取角色列表
        async getRoleList(){
            const {data:result}=await this.$http.get('roles')
            if(result.meta.status!==200){
                this.$message.error('获取角色列表失败')
            }else{
                this.roleList=result.data
                this.$message.success('获取角色列表成功')
            }
        },
        // 添加角色，点击确认的回调
        addRole(){
            this.$refs['addRolesRef'].validate(async (valid)=>{
                if(valid){
                    const {data:result}=await this.$http.post('roles',this.addRoleForm)
                    if(result.meta.status!==201){
                        this.$message.error('添加角色失败')
                    }else{
                        this.addDialogVisible=false //隐藏对话框
                        this.getRoleList() //刷新用户列表
                        this.$message.success('添加角色成功')
                    }
                }
            })
        },
        // 如果关闭对话框就重置表单
        addDialogClose(){
            this.$refs['addRolesRef'].resetFields()
        },

        // 根据 ID 查询角色
        async showEditRole(id){
            const {data:result}=await this.$http.get('roles/'+id)
            if(result.meta.status!==200){
                this.$message.error('查询角色失败')
            }else{
                this.editRoleForm=result.data
                this.editDialogVisible=true
            }
        },
        // 编辑角色，点击确认的回调
        editRole(){
            this.$refs['editRoleRef'].validate(async (valid)=>{
                if(valid){
                    const {data:result}=await this.$http.put('roles'+this.editRoleForm.roleId,{roleName:this.editRoleForm.roleName,roleDesc:this.editRoleForm.roleDesc})
                    if(result.meta.status!==200){
                        this.$message.error('编辑角色失败')
                    }else{
                        this.getRoleList()
                        this.editDialogVisible=false
                        this.$message.success('编辑角色成功')
                    }
                }
            })
        },
        // 如果关闭对话框就重置表单
        editDialogClose(){
            this.$refs['editRoleRef'].resetFields()
        },

        // 删除角色
        async removeRoleById(id){
            // 先有个对话框问操作者是否确认删除
            const confirmResult=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((err)=>{return err})
            // 如果确认删除则返回的是字符串'confirm'，如果取消删除则返回字符串'cancel'
            if(confirmResult!=='confirm'){
                this.$message.info('已取消删除')
            }else{
                const {data:result}=await this.$http.delete('roles'+id)
                if(result.meta.status!==200){
                    this.$message.error('删除失败')
                }else{
                    this.getRoleList()
                    this.$message.success('删除成功')
                }
            }
        },
        // 根据ID删除对应的权限
        async removeRightById(role,rightId){
            // 弹框提示是否要删除
            const confirmResult=await this.$confirm('此操作将删除该权限, 是否继续?', '提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((err)=>{return err})
            if(confirmResult!=='confirm'){
                this.$message.info('已取消操作')
            }else{
                const {data:result}=this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(result.meta.status!==200){
                    this.$message.error('删除权限失败')
                }else{
                    role.children=result.data
                    this.$message.success('删除权限成功')
                }
            }
        },
        // 展示分分配权限的对话框
        async showSetRightDialog(role){
            this.roleId=role.id
            // 获取所有权限的数据
            const {data:result}=await this.$http.get('rights/tree')
            if(result.meta.status!==200){
                this.$message.error('获取权限数据失败')
            }else{
                this.setRightsList=result.data
                // 妙呀~
                this.getdefKeys(role,this.defKeys)
                this.setRightDialogVisible=true
            }
        },
        // 获取当前角色对应的权限并保存到defKeys中
        // #################################################"递归"算法yyds####################################################
        getdefKeys(node,arr){
            // 如果当前节点没有children属性，则是三级节点
            if(!node.children){
                return arr.push(node.id)
            }else{
                node.children.forEach((item)=>{
                    this.getdefKeys(item,arr)
                })
            }
        },
        // 清空数组
        setRightDialogClose(){
            this.defKeys=[]
        },
        // 分配权限，点击确定按钮的回调
        async allotRights(){
            // 根据API文档要求的请求参数，调用一下el-tree内置的两个方法
            const rids=[
                ...this.$refs['setRightsTreeRef'].getCheckedKeys(),
                ...this.$refs['setRightsTreeRef'].getHalfCheckedKeys()
            ].join(',') //数组拼接成字符串
            const {data:result}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:rids})
            if(result.meta.status!==200){
                this.$message.error('分配权限失败')
            }else{
                this.getRoleList()
                this.setRightDialogVisible=false
                this.$$message.success('分配权限成功')
            }
        }
    },
    created(){
        this.getRoleList()
    }
}
</script>

<style lang='less' scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>